package com.hps.spring.cloud.initializrstart.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hps.spring.cloud.initializrstart.service.WeatherDataService;
import com.hps.spring.cloud.initializrstart.vo.WeatherResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;

/**
 * @Author: hps
 * @Description:
 * @Date: Created in 11:19 2018/8/29
 */
@Service
public class WeatherDataServiceImpl implements WeatherDataService {

    private static final String WEATHER_URL = "http://wthrcdn.etouch.cn/weather_mini?";

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ObjectMapper mapper;

    @Override
    public WeatherResponse getDataByCityId(String cityId) {
        String url = WEATHER_URL + "citykey=" + cityId;
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
        return parseWeather(responseEntity.getBody());
    }

    @Override
    public WeatherResponse getDataByCityName(String cityName) {
        String url = WEATHER_URL + "city=" + cityName;
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
        return parseWeather(responseEntity.getBody());
    }

    private WeatherResponse parseWeather(String jsonStr) {
        try {
            return mapper.readValue(jsonStr, WeatherResponse.class);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("Json 解析失败");
        }
    }
}
